package com.ruov.plugin.wx.miniapp.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.ruov.common.annotation.Anonymous;
import com.ruov.common.core.domain.R;
import com.ruov.plugin.wx.miniapp.entity.req.MiniappLoginReq;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.*;

/**
 * @author wjsmc
 * @date 2025/4/23 11:47
 * @description
 **/
@RestController
@AllArgsConstructor
@RequestMapping("/miniapp/{appid}")
@Slf4j
@Anonymous
public class MiniappCommonController {

    private final WxMaService wxMaService;

    @PostMapping("/login")
    public R<String> login(@RequestBody MiniappLoginReq miniappLoginReq, @PathVariable String appid) {
        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
        try {
            WxMaJscode2SessionResult wxMaJscode2SessionResult = wxMaService.jsCode2SessionInfo(miniappLoginReq.getCode());
            return R.ok(wxMaJscode2SessionResult.getOpenid());
        } catch (WxErrorException e) {
            log.error("appid:{},code2Session失败,code{}", appid, miniappLoginReq.getCode(), e);
            return R.fail("登录失败");
        }
    }
}
